package top.mcwebsite.playandroid.business.qa.vm

import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingSource
import androidx.paging.PagingState
import androidx.paging.cachedIn
import top.mcwebsite.playandroid.business.articles.api.model.ArticleModel
import top.mcwebsite.playandroid.business.qa.api.QAApiService
import top.mcwebsite.playandroid.common.network.api.NetworkService
import top.mcwebsite.playandroid.common.network.api.createApi
import top.mcwebsite.playandroid.lib.mvi.base.BaseViewModel
import top.mcwebsite.playandroid.lib.servicemanager.core.ServiceManager

class QAViewModel() : BaseViewModel<QAIntent, QAUiState, QAUiEffect>(
    defaultState = QAUiState()
) {

    private val qaApiService = ServiceManager.getService<NetworkService>()
        .createApi<QAApiService>()

    private val pager = Pager(PagingConfig(pageSize = 10)) {
        QAPagingSource()
    }

    val pagerFlow = pager.flow.cachedIn(viewModelScope)


    override fun handleIntent(intent: QAIntent) {
        when (intent) {
            is QAIntent.OnClickQAItem -> {
                sendUiEffect(QAUiEffect.GoQADetailPageUiEffect(intent.qaItem))
            }
        }
    }

    inner class QAPagingSource : PagingSource<Int, ArticleModel>() {
        override fun getRefreshKey(state: PagingState<Int, ArticleModel>): Int? {
            return null
        }

        override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleModel> {
            return try {
                val nextPageNumber = params.key ?: 1
                val data = qaApiService.qaList(nextPageNumber)
                if (data.errorCode == 0) {
                    LoadResult.Page(
                        data = data.data?.datas ?: emptyList(),
                        prevKey = if (nextPageNumber == 1) null else nextPageNumber - 1,
                        nextKey = if (data.data?.datas.isNullOrEmpty()) null else nextPageNumber + 1
                    )
                } else {
                    LoadResult.Error(RuntimeException("未知错误"))
                }
            } catch (e: Exception) {
                return LoadResult.Error(e)
            }
        }

    }

}